package org.zz.database;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class DbDataGenerate {
	private String driver;
	private String url;
	private String username;
	private String password;
	private String sql;
	private int offset;
	private int skipLineCount;
	private Connection conn;
	private PreparedStatement pstmt;
	private DbDataGenerate parentDbGen = null;
	public DbDataGenerate(String driver, String url, String username,
			String password, String sql, int offset, int skipLineCount) throws ClassNotFoundException, SQLException {
		super();
		this.driver = driver;
		this.url = url;
		this.username = username;
		this.password = password;
		this.sql = sql;
		this.offset = offset;
		this.skipLineCount = skipLineCount;
		Class.forName(driver);
		conn = DriverManager.getConnection(url, username, password);
		pstmt = (PreparedStatement) conn.prepareStatement(sql + " limit ?," + skipLineCount);
		
	}
	
	public void close(){
		try {
			pstmt.close();
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public ArrayList<Object> getNextSet(Object obj){
		MemberAccess memberAccess = new MemberAccess();
		memberAccess.init(obj);
		Object object = null;
		ResultSet resSet = null;
		ArrayList<Object> resList = new ArrayList<Object>();
		try {
			pstmt.setInt(1, offset);
			resSet = pstmt.executeQuery();
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if(resSet != null){
			int lineCount = 0;
			try {
				while(resSet.next()){
					++lineCount;
					try {
						object = obj.getClass().newInstance();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						break;
					}
					for(String field: memberAccess.getFields()){
						MemberAccess.Write(object, field, resSet.getObject(field));
					}
					resList.add(object);
				}
				resSet.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			offset += lineCount;
		}
//		if(resList.size() == 0){
//			System.out.println("Zero param");
//		}
		return resList;
	}
	
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		DbDataGenerate dbDataGenerate = new DbDataGenerate("com.mysql.jdbc.Driver","jdbc:mysql://localhost:3306/test","root","security","SELECT id id,title title,abstract abst FROM paper",0,1000);
		ArrayList<Object> list = null;
//		while((list = dbDataGenerate.getNextSet(new Article())) != null){
//			for(Object obj: list)
//				System.out.println(obj.toString());
//		}
		dbDataGenerate.close();
	}
}
